CPPSTD		?= --std=c++20 
CPPFLAGS	+= $(CPPSTD)

PARENT_DISTDIR	?= ../out

override CPPFLAGS	+= -MMD -MP
override CPPFLAGS	+= -I../source -I../include
override CPPFLAGS	+= $(shell cat ../.cxxflags 2> /dev/null | xargs )
override CPPFLAGS	+= $(shell cat .cxxflags 2> /dev/null | xargs )
override LDFLAGS	+= $(shell cat ../.ldflags 2> /dev/null | xargs )
override LDFLAGS	+= $(shell cat .ldflags 2> /dev/null | xargs )
override LDLIBS		+= $(shell cat ../.ldlibs 2> /dev/null | xargs )
override LDLIBS		+= $(shell cat .ldlibs 2> /dev/null | xargs )

TEMPDIR	:= temp
ifneq ($(LOCAL_TEMP),)
TEMPDIR	:= $(TEMPDIR)/$(LOCAL_TEMP)
endif

DISTDIR	:= .
LIB := lib
PARENTLIB := ../lib
ifneq ($(LOCAL_DIST),)
DISTDIR	:= $(DISTDIR)/$(LOCAL_DIST)
LIB := $(LIB)/$(LOCAL_DIST)
PARENTLIB := $(PARENTLIB)/$(LOCAL_DIST)
endif

override LOCALIB	+= $(wildcard $(LIB)/*.a)
override LOCALIB	+= $(wildcard $(PARENTLIB)/*.a)
override LOCALIB	+= $(wildcard $(PARENT_DISTDIR)/*.a)
override LDFLAGS	+= -L$(PARENT_DISTDIR) -L$(LIB) -L$(PARENTLIB)

SOURCES	:= $(shell echo *.cpp)
TARGETS	:= $(SOURCES:%.cpp=$(DISTDIR)/%.test)
OBJECTS	:= $(SOURCES:%.cpp=$(TEMPDIR)/%.o)
DEPENDS	:= $(OBJECTS:.o=.d)
RUNS	:= $(OBJECTS:.o=.run)

run: $(RUNS)

build: $(TARGETS)

$(TEMPDIR)/%.run: $(DISTDIR)/%.test
	./$<
	@echo "This is a dummy file for make to keep track of test runs" > $@

$(DISTDIR)/%.test: $(TEMPDIR)/%.o $(LOCALIB)
	$(CXX) $(LDFLAGS) $< $(LOCALIB) $(LDLIBS) -o $@

$(TEMPDIR)/%.o: %.cpp | $(TEMPDIR)
	$(CXX) $(CPPFLAGS) $(CXXFLAGS) -o $@ -c $<

$(TEMPDIR):
	@mkdir $@

cleanrun:
	@rm $(RUNS) 2> /dev/null || true

clean: cleanrun
	@rm $(DEPENDS) 2> /dev/null || true
	@rm $(OBJECTS) 2> /dev/null || true
	@rmdir -p $(TEMPDIR) 2> /dev/null || true
	@rm $(TARGETS) 2> /dev/null || true
	@echo All clean!

-include $(DEPENDS)

.PRECIOUS : $(OBJECTS) $(TARGETS)
.PHONY : clean cleanrun
